/*
Copyright (c) 2013 Mihail Volkov

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#if defined(__GNUC__) && defined(WIN32)
// hack against mingw's winsock header fuckup
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#endif

#include "htmd_winsocklocal.h"

#ifndef DISABLE_HTMD

#include <stdlib.h>
#include <stdio.h>

#ifdef _MSC_VER
// library linkage shortcut for M$V$
#pragma comment (lib, "Ws2_32.lib")
#endif


HtMdConnection_WinsockLocal::HtMdConnection_WinsockLocal (const std::string &port):
	mWsaError (0),
	mListenSocket (INVALID_SOCKET),
	mClientSocket (INVALID_SOCKET),
	mPrompt (std::string ("127.0.0.1:")+port),
	mInitStage (IS_NONE)
{
#define CTOR_FAIL do { mConnState = DEFUNCT; doDeinit (); return; } while (0)
	// init CS
	InitializeCriticalSection (&mLockCS);

	// init winsock
	if (WSAStartup(MAKEWORD(2,2), &mWsaData)!=0)
		CTOR_FAIL;
	mInitStage = IS_WSA_STARTUP;

	// set
	struct addrinfo hints;
	ZeroMemory(&hints,sizeof (hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;
	hints.ai_flags = AI_PASSIVE;
	if (getaddrinfo (NULL,port.c_str (),&hints,&mpAddrInfo)!=0)
		CTOR_FAIL;
	mInitStage = IS_GETADDR;

	// Create a SOCKET for connecting to server
	mListenSocket = socket
		(mpAddrInfo->ai_family,
		mpAddrInfo->ai_socktype,
		mpAddrInfo->ai_protocol);
	if (mListenSocket == INVALID_SOCKET)
    	CTOR_FAIL;
	mInitStage = IS_CREATESOCKET;

	// Setup the TCP listening socket
    if (bind (mListenSocket,mpAddrInfo->ai_addr,(int)mpAddrInfo->ai_addrlen)
    	==SOCKET_ERROR)
		CTOR_FAIL;
	u_long mode = 1;
	if (ioctlsocket (mListenSocket,FIONBIO,&mode)==SOCKET_ERROR)
		CTOR_FAIL;
	mInitStage = IS_SETUPSOCKET;

	if (listen (mListenSocket,1)==SOCKET_ERROR)
		CTOR_FAIL;
	mInitStage = IS_LISTEN;
#undef CTOR_FAIL

	mInitStage = IS_ALL_OK;
	mConnState = NOT_CONNECTED;
}

HtMdConnection_WinsockLocal::~HtMdConnection_WinsockLocal ()
{
	doDeinit ();
	DeleteCriticalSection (&mLockCS);
}

void HtMdConnection_WinsockLocal::doDeinit ()
{
	if (mInitStage>IS_NONE && mInitStage<IS_ALL_OK)
		mWsaError = WSAGetLastError ();
	switch (mInitStage)
	{
	case IS_ALL_OK:
		if (mClientSocket!=INVALID_SOCKET)
			closesocket (mClientSocket);
	case IS_LISTEN:
	case IS_SETUPSOCKET:
	case IS_CREATESOCKET:
		closesocket (mListenSocket);
	case IS_GETADDR:
		freeaddrinfo (mpAddrInfo);
	case IS_WSA_STARTUP:
		WSACleanup ();
	default:;
	}
	mInitStage = IS_NONE;
}

bool HtMdConnection_WinsockLocal::isOpenOk () const
{
	return mInitStage==IS_ALL_OK;
}

std::string HtMdConnection_WinsockLocal::getConnectionUserPrompt ()
{
	return mPrompt;
}

HtMdConnection::ConnectionState HtMdConnection_WinsockLocal::getState ()
{
	return mConnState;
}

void HtMdConnection_WinsockLocal::pollForInboundConnection ()
{
	if (mConnState==DEFUNCT) return;
	SOCKET clientSocket = accept (mListenSocket,NULL,NULL);
	if (clientSocket!=INVALID_SOCKET)
	{
		if (mConnState==NOT_CONNECTED)
		{
			u_long mode = 1;
			if (ioctlsocket (clientSocket,FIONBIO,&mode)==SOCKET_ERROR)
			{
				// failed to set client socket in async mode...
				// bad luck for the client
				closesocket (clientSocket);
				return;
			}
			mClientSocket = clientSocket;
			mConnState = CONNECTED;
		}
		else
		{
			// already connected - kick other clients
			closesocket (clientSocket);
		}
	}
}

void HtMdConnection_WinsockLocal::closeInboundConnection ()
{
	if (mConnState==CONNECTED)
	{
		closesocket (mClientSocket);
		mConnState = NOT_CONNECTED;
	}
}

int HtMdConnection_WinsockLocal::tryRead (HtMdChunkDesc buf)
{
	if (mConnState!=CONNECTED) return 0;
	int result = recv (mClientSocket,(char *)buf,buf.getLength (),0);
	if ((buf.getLength ()>0 && result==0)
		|| (result==SOCKET_ERROR &&
		WSAGetLastError ()!=WSAEWOULDBLOCK &&
		WSAGetLastError ()!=WSAENOBUFS))
	{
		closesocket (mClientSocket);
		mClientSocket = INVALID_SOCKET;
		mConnState = NOT_CONNECTED;
		return 0;
	}
	else
		return result==SOCKET_ERROR? 0 : result;
}

int HtMdConnection_WinsockLocal::tryWrite (const HtMdConstChunkDesc &data)
{
	if (mConnState!=CONNECTED) return 0;
	int result = send (mClientSocket,(const char *)data,data.getLength (),0);
	if (result==SOCKET_ERROR)
	{
		if (WSAGetLastError ()==WSAEWOULDBLOCK &&
			WSAGetLastError ()==WSAENOBUFS)
			return 0; // looks like normal non-blocking situation
		// otherwise, looks like connection dropped
		closesocket (mClientSocket);
		mClientSocket = INVALID_SOCKET;
		mConnState = NOT_CONNECTED;
		return 0;
	}
	else
		return result==SOCKET_ERROR? 0 : result;
}

bool HtMdConnection_WinsockLocal::tryRecursiveLock ()
{
	return (bool)TryEnterCriticalSection (&mLockCS);
}

void HtMdConnection_WinsockLocal::recursiveLock ()
{
	EnterCriticalSection (&mLockCS);
}

void HtMdConnection_WinsockLocal::recursiveUnlock ()
{
	LeaveCriticalSection (&mLockCS);
}

#endif // DISABLE_HTMD
